package cn.javaxc.mvcwork.action;
import cn.javaxc.mvcwork.controller.*;
import cn.javaxc.mvcwork.framework.actions.*;
import cn.javaxc.mvcwork.framework.database.ConnectionElement;
import cn.javaxc.mvcwork.modules.file.*;
import cn.javaxc.mvcwork.util.helper.*;
import cn.javaxc.mvcwork.util.common.*;
import cn.javaxc.mvcwork.util.io.FileDownload;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.*;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.*;
import javax.swing.ImageIcon;
import javax.swing.filechooser.FileSystemView;
import cn.javaxc.mvcwork.controller.AppUtils;
import cn.javaxc.mvcwork.modules.login.UserBean;
import org.springframework.security.core.userdetails.UserDetails;

//icon

/**
 * A stand alone servlet that sends files. Currently it will stream an image
 * file from a protected image library
 *
 *
 * @mvcversion 1.0
 *
 */
public class MVCFileAction extends TModuleAction {
  


  protected boolean doUserPermission(){
	UserDetails userSession = MSecurityUtils.getUserEntity();
	if (userSession != null && userSession.getUsername()!=null) {
		return true;
	}
	return false;
  }

 public String executeDownloadFile() {
	if(!doUserPermission())return PermissionError;
    Exception errorMessage = null;
    Object fileid = CommonUtil.parseInt(RequestHelper.getRequestValue(context.getRequest(),"fileid")+"",-1);
	int fileverid = CommonUtil.parseInt(RequestHelper.getRequestValue(context.getRequest(),"fileverid")+"",-1);
	if (StringUtils.isNullData(fileid)&&fileverid==-1){
		context.setActionError( "参数错误,无效文件ID");
		return (SystemError); 
	  }
	String view = context.getParameter("view");
	double version = 1.0;
    FileItem thisItem = null;
//    try {
	  if (StringUtils.isNullData(fileid)){
		FileItemVersion ver=new FileItemVersion();
		ver.queryRecord(fileverid,context);
		fileid=ver.getItemId();
		version=ver.getVersion();
	  }
      thisItem = new FileItem(fileid);
	  if (fileverid != -1) {
        thisItem.buildVersionList();
      }
//    } catch (Exception e) {
//		
//      context.setError( e);
//      return (SystemError);
//    }

    //Start the download
    try {
	  if (fileverid == -1) {
      FileItem itemToDownload = thisItem;
      itemToDownload.setEnteredBy(CommonUtil.parseInt(MSecurityUtils.getUserId()));
      String filePath = AppUtils.getModuleFileLibrary(context,thisItem.getLinkModuleId()) + AppUtils.getDatePath(
          itemToDownload.getModified()) + itemToDownload.getFilename();

      FileDownload fileDownload = new FileDownload();
      fileDownload.setFullPath(filePath);
      fileDownload.setDisplayName(itemToDownload.getClientFilename());
      if (fileDownload.fileExists()) {
        if (view != null && "true".equals(view)) {
            fileDownload.streamContent(context);
          } else {
            fileDownload.sendFile(context);
          }
        //Get a db connection now that the download is complete
        itemToDownload.updateCounter();
      } else {
        FrameLog.info(
            "ProductCatalogs-> Trying to send a file that does not exist");
        context.setActionError( "系统中的请求下载不再存在");
        return (SystemError);
      }
	  }else {
        FileItemVersion itemToDownload = thisItem.getVersion(version);
        itemToDownload.setEnteredBy(CommonUtil.parseInt(MSecurityUtils.getUserId()));
        String filePath = AppUtils.getModuleFileLibrary(context,thisItem.getLinkModuleId())  + AppUtils.getDatePath(
            itemToDownload.getModified()) + itemToDownload.getFilename();
        FileDownload fileDownload = new FileDownload();
        fileDownload.setFullPath(filePath);
        fileDownload.setDisplayName(itemToDownload.getClientFilename());
        if (fileDownload.fileExists()) {
          if (view != null && "true".equals(view)) {
            fileDownload.streamContent(context);
          } else {
            fileDownload.sendFile(context);
          }
          //Get a db connection now that the download is complete
          itemToDownload.updateCounter();
        } else {
          FrameLog.info(
              "LeadsDocuments-> Trying to send a file that does not exist");
          context.setActionError( "系统中的请求下载不再存在");
          return (SystemError);
        }
      }
    } catch (java.net.SocketException se) {
		
      //User either cancelled the download or lost connection
      if (System.getProperty("DEBUG") != null) {
        System.out.println(se.toString());
      }
    } catch (Exception e) {
		
      errorMessage = e;
      FrameLog.info(e.toString());
    }
    if (errorMessage == null) {
      return null;
    } else {
      context.setError( errorMessage);
      return (SystemError);
    }
	
  }



	public String executeGetLibFile() throws Exception{

			String file=context.getParameter("file");
			String lib=context.getParameter("lib");
			if (file!=null){
				file=context.getRequest().getRealPath("/WEB-INF/fileLibrary/"+AppUtils.getDbName(context)+"/"+lib+file);

				if(file==null)return null;

				String view = context.getParameter("view");

				File base=new File(context.getRequest().getRealPath("/WEB-INF/fileLibrary/"),AppUtils.getDbName(context));
				File ffile=new File(file);
				if(ffile.getCanonicalPath().toLowerCase().indexOf(base.getCanonicalPath().toLowerCase())!=0){
					context.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN, file);
				}
				FileDownload fileDownload = new FileDownload();
				fileDownload.setFullPath(ffile.getAbsolutePath());
				fileDownload.setDisplayName(ffile.getName());

				if (fileDownload.fileExists()) {
				  if (view != null && "true".equals(view)) {					
					fileDownload.streamContent(context);
				  } else {
					fileDownload.sendFile(context);
				  }
				}else{
					context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, file);
				}
			}else{
					context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, file);
				}


		
		return null;
	}


}
